package top.jingles.utils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;

public class SimpleHttpServer {
    int port;
    Map<String, HttpHandler> handlers;

    public SimpleHttpServer(int port) {
        this.port = port;
        handlers = new HashMap<>();
    }

    public void addHandler(String url, HttpHandler handler) {
        handlers.put(url, handler);
    }

    public void startServer() throws IOException {
        HttpServerProvider provider = HttpServerProvider.provider();
        HttpServer httpServer = provider.createHttpServer(new InetSocketAddress(port), 100);

        for (Entry<String, HttpHandler> entry : handlers.entrySet()) {
            httpServer.createContext(entry.getKey(), entry.getValue());
        }

        httpServer.setExecutor(null);  
        httpServer.start();  
        System.out.println("server started");
    }
}
